import gcoord from 'gcoord';
import defaultColors from './data/colors.json';

const transformPoint = point => {
  if (point.csysType && point.csysType !== 'GCJ02') return {
    coordinates: gcoord.transform(point.coordinates, gcoord[point.csysType], gcoord.GCJ02),
    properties: point.properties,
  };
  return {
    coordinates: point.coordinates,
    properties: point.properties,
  };
}

const transformCollection = data => {
  if (Array.isArray(data)) {
    return data.map(item => transformPoint(item));
  } else {
    return [transformPoint(data)];
  }
}

class Map {
  data = []
  center = null
  colors = defaultColors
  
  setData = (source, autoSetFitView = true) => {
    if (!source) return;
    this.data = transformCollection(source);
    if (this.setMapData) this.setMapData(this.data);
    if (autoSetFitView && this.data.length > 0) this.setCenter(this.data[0]);
  }

  addData = (source, autoSetFitView = true) => {
    if (!source) return;
    this.data = Array.isArray(this.data) ? this.data : [];
    const data = transformCollection(source);
    this.data.push(...data);
    if (this.setMapData) this.setMapData(this.data);
    if (autoSetFitView && data.length > 0) this.setCenter(data[0]);
  }

  clearData = () => {
    this.data = [];
    if (this.clearMapData) this.clearMapData();
  }

  setCenter = (center = null) => {
    if (!center) return;
    this.center = transformPoint(center);
    if (this.setMapCenter) this.setMapCenter(this.center);
  }

  setColors = colors => {
    this.colors = Array.isArray(this.colors) ? this.colors : defaultColors;
    if (Array.isArray(colors) && colors.length > 0) {
      this.colors = colors;
    }
    if (this.setMapColors) this.setMapColors(this.colors);
  }

  setMapData = null
  setMapCenter = null
  setMapColors = null
  clearMapData = null
}

window.myMap = new Map();
